package net.yebaihe.buildapp.yyh;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class FillContent extends Activity {
	private String baseDir=Environment.getExternalStorageDirectory().getAbsolutePath()+"/buildapp/";
	private HashMap<Integer,View> retmap=new HashMap<Integer,View>();  
	private HashMap<Integer,String>valuemap=new HashMap<Integer,String>();
	int versionCode=1;
	private String validHint="校验错误";
	private String checkPoint;
	private String appIcon;
	private String appCName;
	private String appEName;
	//private int appId=-1;
	private int appTId;
	private int appidx;
	private int tempidx;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content);
        
        new File(baseDir).mkdirs();
        tempidx=getIntent().getIntExtra("tempidx", -1);
        appidx=getIntent().getIntExtra("appidx", -1);
        if (appidx>=0){
        	//Toast.makeText(this, "appidx是"+appidx, Toast.LENGTH_LONG).show();
        	updateValueMap();
        }
        fillContent(tempidx);
        
        Button b=(Button) this.findViewById(R.id.btnsavecnt);
        b.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				MyHelper dbhelper = MyHelper.get(FillContent.this);
				SQLiteDatabase db = dbhelper.getReadableDatabase();
				if (doValidate(db)){
					doSave();
				}
				else{
					Toast.makeText(FillContent.this, checkPoint+":"+validHint, Toast.LENGTH_LONG).show();
				}
				db.close();
				dbhelper.close();
			}
        });

        Button b2=(Button) this.findViewById(R.id.btnsubmitcnt);
        b2.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				MyHelper dbhelper = MyHelper.get(FillContent.this);
				SQLiteDatabase db = dbhelper.getReadableDatabase();
				if (doValidate(db)){
					doSave();
					doSubmit();
				}
				else{
					Toast.makeText(FillContent.this, checkPoint+":"+validHint, Toast.LENGTH_LONG).show();
				}
				db.close();
				dbhelper.close();
			}
        });
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
  
    }

	protected void doSubmit() {
		updateValueMap();
		
		String cnt="";
		Iterator<Integer> iter = valuemap.keySet().iterator(); 
		while (iter.hasNext()){
			Integer key = iter.next();
			String value=valuemap.get(key);
			cnt+=key+":"+value+"\n";
		}
		
		/*new AlertDialog.Builder(this).setTitle("提交")
		.setMessage(cnt).create().show();*/
		
		Intent i=new Intent(this,FillAdInfo.class);
		i.putExtra("appidx", appidx);		
		startActivity(i);
		
	}

	private void updateValueMap() {
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		
		Cursor cursor=db.rawQuery("select * from aparams where aid="+appidx, null);
		if (cursor.moveToFirst()){
			do{
				valuemap.put(cursor.getInt(2),cursor.getString(3));
			}while (cursor.moveToNext());
		}
		cursor.close();

		cursor=db.rawQuery("select * from app where _id="+appidx, null);
		if (cursor.moveToFirst()){
			valuemap.put(-1,cursor.getString(5));
			versionCode=cursor.getInt(5);
			valuemap.put(-2,cursor.getString(1));
			valuemap.put(-3,cursor.getString(2));
			valuemap.put(-4,cursor.getString(3));
		}
		tempidx=cursor.getInt(4);
		cursor.close();
		
		db.close();        	
	}

	protected void doSave() {
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getWritableDatabase();
		Iterator<Integer> iter = retmap.keySet().iterator(); 
		
		if (appidx<0){
			String sql="insert into app (cname,ename,icon,tid,versioncode) values ('"+
			appCName+"','"+
			appEName+"','"+
			appIcon+"',"+
			appTId+","+
			versionCode+")";
			Log.d("myown", sql);
			db.execSQL(sql); 
			Cursor cursor = db.rawQuery("select * from app ORDER BY _id desc limit 1", null);
			if (cursor.moveToFirst()){
				appidx=cursor.getInt(0);
				cursor.close();
			}
			else{
				cursor.close();
				Toast.makeText(this, "创建应用的时候数据库操作失败！", Toast.LENGTH_LONG).show();
				return;
			}
			Toast.makeText(this, "新创建的ID是:"+appidx, Toast.LENGTH_LONG).show();
		}
		else{
			String sql="update app set cname='"+appCName+"',ename='"+appEName+"',icon='"+appIcon+"',tid="+appTId+",versioncode="+versionCode+" where _id="+appidx;
			db.execSQL(sql);
		}
		
		String sql="delete from aparams where aid="+appidx+" and tid>=0";
		db.execSQL(sql, new Object[]{});
		
		while (iter.hasNext()){
			Integer key = iter.next();
			View value=retmap.get(key);
			String svalue=getValueFromView(value);
			if (key>=0){
				db.execSQL("insert into aparams (aid,tid,value) values ("+appidx+","+key+",'"+svalue+"')");
			}
		}
		db.close();
		Toast.makeText(this, "保存成功！", Toast.LENGTH_LONG).show();
	}

	protected boolean doValidate(SQLiteDatabase db) {
		Iterator<Integer> iter = retmap.keySet().iterator(); 
		while (iter.hasNext()){
			Integer key = iter.next();
			View value=retmap.get(key);
			String svalue=getValueFromView(value);
			if (key>=0){
				Cursor cursor = db.rawQuery("select * from tparams where _id="+key,null);
				cursor.moveToFirst();
				checkPoint=cursor.getString(3);
				String[] typedef=cursor.getString(4).split(":");
				int ptype=Integer.parseInt(typedef[0]);
				switch (ptype){
				case 1:
					if (!validFile(svalue,typedef)) return false;
					break;
				case 2:
					String[] files=svalue.split(";");
					for (int i=0;i<files.length;i++){
						String[] finfo=files[i].split(":");
						checkPoint=checkPoint+"("+finfo[0]+")";
						if (!validFile(finfo[0],typedef)){
							return false;
						}
						String title="";
						if (finfo.length>=2){
							title=finfo[1];
						}
						if (!validString(title)){
							return false;
						}
					}
					break;
				case 3:
					if (!validString(svalue)) return false;
					break;
				}
				cursor.close();
			}
			else{
				switch (key){
				case -4:
					checkPoint="软件图标";
					appIcon=svalue;
					if (!validPng(svalue,72,72)) return false;
					break;
				case -2:
					checkPoint="软件中文名称";
					appCName=svalue;
					if (!validCName(svalue)) return false;
					break;
				case -3:
					checkPoint="软件英文名称";
					appEName=svalue;
					if (!validEName(svalue)) return false;
					break;
				}
			}
		}
		return true;
	}

	private boolean validEName(String svalue) {
		for (int i=0;i<svalue.length();i++){
			if ((svalue.charAt(i)<'a') || (svalue.charAt(i)>'z')){
				validHint="英文名称必须是小写英文字母:"+svalue;
				return false;
			}
		}
		return validString(svalue);
	}

	private boolean validCName(String svalue) {
		return validString(svalue);
	}

	private boolean validString(String svalue) {
		validHint="字符串长度不能为空";
		return svalue.length()>0;
	}

	private boolean validPng(String svalue, int w, int h) {
		Options opts=new Options();
		opts.inJustDecodeBounds=true;
		BitmapFactory.decodeFile(svalue, opts);
		validHint="图片无效或者长宽不符合要求："+w+"x"+h;
		return (opts.outWidth==w) && (opts.outHeight==h);
	}

	private boolean validFile(String svalue, String[] typedef) {
		if (typedef[1].equals("png")){
			return validPng(svalue,Integer.parseInt(typedef[2]),Integer.parseInt(typedef[3]));
		}
		else if (typedef[1].equals("txt")){
			validHint="文件不存在或者为空";
			return svalue.length()>0 && new File(svalue).exists();
		}
		return false;
	}

	private String getValueFromView(View value) {
		if (value instanceof EditText){
			EditText v=(EditText) value;
			return v.getText().toString();
		}
		else if (value instanceof CheckBox){
			CheckBox v=(CheckBox) value;
			if (v.isChecked()) return "Y";
			return "N";
		}
		else if (value instanceof TextView){
			TextView v=(TextView) value;
			return v.getText().toString();
		}
		else if (value instanceof LinearLayout){
			LinearLayout l=(LinearLayout) value;
			String ret="";
			for (int i=0;i<l.getChildCount();i++){
				View vs1=l.getChildAt(i);
				if (vs1 instanceof TextView){//多选文件的文件路径
					ret+=((TextView) vs1).getText().toString()+":";
				}
				else if (vs1 instanceof LinearLayout){
					LinearLayout vsl=(LinearLayout)vs1;
					EditText t=(EditText) vsl.getChildAt(1);
					ret+=t.getText().toString()+";";
				}
 			}
			return ret;
		}
		else{
			return (String) value.getTag();
		}
	}

	private void fillContent(int id) {
		appTId=id;
		LinearLayout l=(LinearLayout) this.findViewById(R.id.idcontent);
		
		fillSubContent(l,"版本号",4,-1,"自动维护，每次提交的时候加1，用作软件的内部版本号");
		fillSubContent(l,"中文名称",3,-2,"此名称是所创建app的中文名称，可以用任何字符");
		fillSubContent(l,"英文名称",3,-3,"此名称通常作为包名的最后一部分,只能用小写的英文字符");
		fillSubContent(l,"软件图标",1,-4,"72x72像素的PNG图片");
		
		MyHelper dbhelper = MyHelper.get(this);
		SQLiteDatabase db = dbhelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from tparams where tid="+id,null);
		if (cursor.moveToFirst()){
			do{
				fillSubContent(l,cursor);
			}while (cursor.moveToNext());
		}
		cursor.close();
		db.close();
	}

	private void fillSubContent(LinearLayout l, String title, int type, int idx,String desc) {
		LinearLayout ll=new LinearLayout(this);
		TextView v=new TextView(this);
		v.setText(title);
		LayoutParams params = new LinearLayout.LayoutParams(100, ViewGroup.LayoutParams.WRAP_CONTENT);
		//params.weight=1;
		ll.addView(v,params);
		
		final int id=idx;
		
		switch (type){
		case 1:{
			TextView v2=new TextView(this);
			if (valuemap.containsKey(idx)) v2.setText(valuemap.get(idx));
			params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
			params.weight=1;
			ll.addView(v2,params);
			retmap.put(id, v2);
			
			Button b=new Button(this);
			b.setTag(idx);
			b.setText("选择");
			b.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					Intent i=new Intent(FillContent.this,ChooseFiles.class);
					i.putExtra("index", id);
					i.putExtra("base", baseDir);
					i.putExtra("mode", "single");
					startActivityForResult(i,0);
				}
			});
			ll.addView(b);
		}
		break;
		case 2:{
			LinearLayout v2=new LinearLayout(this);
			v2.setOrientation(LinearLayout.VERTICAL);
			params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
			params.weight=1;
			ll.addView(v2,params);
			retmap.put(id, v2);
			if (valuemap.containsKey(idx)){ 
				fillType2Value(v2,valuemap.get(idx));
			}
			
			Button b=new Button(this);
			b.setTag(idx);
			b.setText("选择");
			b.setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View arg0) {
					Intent i=new Intent(FillContent.this,ChooseFiles.class);
					i.putExtra("index", id);
					i.putExtra("base", baseDir);
					i.putExtra("mode", "multiple");
					startActivityForResult(i,0);
				}
			});
			ll.addView(b);
		}
		break;
		case 3:{
			EditText e=new EditText(this);
			if (valuemap.containsKey(idx)) e.setText(valuemap.get(idx));
			retmap.put(id, e);
			params=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);			
			params.weight=1;
			ll.addView(e,params);			
		}
		break;
		case 4:{
			TextView ver=new TextView(this);
			if (valuemap.containsKey(idx)) ver.setText(valuemap.get(idx));
			retmap.put(id, ver);
			ver.setText(""+versionCode);
			params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
			params.weight=1;
			ll.addView(ver,params);
		}
		break;
		case 5:{
			CheckBox ver=new CheckBox(this);
			if (valuemap.containsKey(idx)) ver.setChecked(valuemap.get(idx).equals("Y"));
			retmap.put(id, ver);
			ll.addView(ver);
		}
		break;
		}
		
		Button descbtn=new Button(this);
		descbtn.setTag(desc);
		descbtn.setText("说明");
		descbtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(FillContent.this).setTitle(R.string.app_name).setMessage(""+v.getTag())
				.setPositiveButton("确定", null)	
				.setIcon(R.drawable.icon).create().show();
			}
		});
		ll.addView(descbtn);
		
		l.addView(ll);
	}

	private void fillType2Value(LinearLayout l, String files) {
		l.removeAllViews();
		String[] fs=files.split(";");
		for (int i=0;i<fs.length;i++){
			TextView v1=new TextView(this);
			String[] finfo=fs[i].split(":");
			v1.setText(finfo[0]);
			l.addView(v1);
			String title="";
			if (finfo.length>1){
				title=finfo[1];
			}
			LinearLayout memo=new LinearLayout(this);
			TextView v3=new TextView(this);
			v3.setText("第"+(i+1)+"节标题：");
			memo.addView(v3);
			EditText e=new EditText(this);
			e.setText(title);
			memo.addView(e,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
			l.addView(memo);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode!=RESULT_OK) return;
		String files=data.getStringExtra("files");
		int rowidx=data.getIntExtra("index", -1000);
		//Toast.makeText(this, rowidx+":"+files, Toast.LENGTH_LONG).show();
		View v=retmap.get(rowidx);
		v.setTag(files);
		if (v instanceof TextView){
			String vccc=data.getStringExtra("files").split(";")[0];
			v.setTag(vccc);
			TextView tv=(TextView)v;
			tv.setText(vccc);
		}
		else if (v instanceof LinearLayout){
			LinearLayout l=(LinearLayout) v;
			fillType2Value(l,files);
		}
	}
	
	private void fillSubContent(LinearLayout l, Cursor cursor) {
		String stype=cursor.getString(4).split(":")[0];
		fillSubContent(l,cursor.getString(3),Integer.parseInt(stype),cursor.getInt(0),cursor.getString(5));
	}

}
